package paginate

// Pager 通用的分页信息
type Pager struct {
	Page     int   `json:"page"`                //当前页码
	Size     int   `json:"size"`                //单页数量
	PagingId int64 `json:"paging_id,omitempty"` //分页用id，用于辅助分页用，可为主键id值

	Total     int64 `json:"total"`      //总条数
	PageCount int64 `json:"page_count"` //总页数
}

const PageSizeMax = 1000

func (pa *Pager) SetTotal(total int64) {
	pa.Total = total
	pa.Correct()
}

func (pa *Pager) Correct() {
	if pa.Page <= 0 {
		pa.Page = 1
	}
	if pa.Size <= 0 || pa.Size > PageSizeMax {
		pa.Size = 20
	}
	pa.PageCount = 0
	if pa.Total > 0 {
		pa.PageCount = (pa.Total-1)/int64(pa.Size) + 1
	}
}

func (pa *Pager) Offset() int {
	return (pa.Page - 1) * pa.Size
}

func NewPager(page, size int) *Pager {
	p := &Pager{
		Page: page,
		Size: size,
	}
	p.Correct()
	return p
}
